<template>
	<div class="manage">
		<div class="manage_content">
			<div class="search_wrap">
				<el-input v-model="query.name" placeholder="院系" clearable></el-input>
				<el-button @click="searchHandle" type="primary">搜索</el-button>
				<el-button @click="addHandle" type="primary"><i class="el-icon-circle-plus"></i> 新增院系</el-button>
			</div>
			<!-- 表格 -->
			<template>
				<el-table :data="tableData" border style="width: 100%" stripe class="my_table">
					<el-table-column prop="name" label="院系" width="160">
					</el-table-column>
					<el-table-column prop="createTime" label="辅导员">
						<template slot-scope="scope">
							<span v-if="item.type==1" v-for="item in scope.row.admins" class="mar_rig10">{{item.name}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="createTime" label="院系管理员">
						<template slot-scope="scope">
							<span v-if="item.type==2" v-for="item in scope.row.admins" class="mar_rig10">{{item.name}}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="600">
						<template slot-scope="scope">
							<el-button @click="guanLianHandle(scope.row, scope.$index, 1)" type="success" size="small" plain> <i class="el-icon-connection"></i> 辅导员</el-button>
							<el-button @click="guanLianHandle(scope.row, scope.$index, 2)" type="success" size="small" plain> <i class="el-icon-connection"></i> 院系管理员</el-button>
							<el-button @click="guanLianHandle4(scope.row, scope.$index)" type="info" size="small" plain> <i class="el-icon-connection"></i> 院系学生部门</el-button>
							<el-button @click="editHandle(scope.row)" type="primary" size="small"><i class="el-icon-edit"></i></el-button>
							<el-button @click="deleteHandle(scope.row)" type="danger" size="small"><i class="el-icon-delete"></i></el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>
			<!-- 分页 -->
			<div class="pagination_wrap">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.page" :page-size="query.size" background layout="sizes, prev, pager, next, total" :total="total">
				</el-pagination>
			</div>
			<!-- 新增院系 -->
			<el-dialog title="新增院系" :visible.sync="dialogVisible" width="30%" center>
				<el-form :model="addData" :rules="rules" ref="ruleForm" label-position="right" label-width="100px">
					<el-form-item label="院系名称" prop="name">
						<el-input v-model="addData.name" placeholder="请输入院系名称" clearable></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </span>
			</el-dialog>
			<!-- 修改院系 -->
			<el-dialog title="修改院系" :visible.sync="dialogVisible1" width="30%" center>
				<el-form :model="editData" :rules="rules" ref="ruleForm1" label-position="right" label-width="100px">
					<el-form-item label="院系名称" prop="name">
						<el-input v-model="editData.name" placeholder="请输入院系名称" clearable></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="submitForm1('ruleForm1')">确 定</el-button>
        </span>
			</el-dialog>
			<!-- 关联院系管理员 -->
			<el-dialog title="关联院系管理员" :visible.sync="dialogVisible3" center>
				<template>
					<el-transfer @change="changeTransferHandle" v-model="transferList" filterable :filter-method="filterMethod" filter-placeholder="请输入院系管理员" :data="OperatorList3" :titles="transferTitles" :button-texts="['解绑', '绑定']" class="my_transfer"></el-transfer>
				</template>
			</el-dialog>
			<!-- 关联辅导员 -->
			<el-dialog title="关联辅导员" :visible.sync="dialogVisible2" center>
				<template>
					<el-transfer @change="changeTransferHandle" v-model="transferList" filterable :filter-method="filterMethod2" filter-placeholder="请输入辅导员" :data="OperatorList2" :titles="transferTitles" :button-texts="['解绑', '绑定']" class="my_transfer"></el-transfer>
				</template>
			</el-dialog>
			<!-- 关联部门 -->
			<el-dialog title="关联院系部门学生" :visible.sync="dialogVisible4" center>
				<template>
					<el-tree :data="deptTree" :props="defaultProps" show-checkbox :default-checked-keys="defaultCheckedKeys" node-key="id" ref="tree">
					</el-tree>
				</template>
				<span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible4 = false">取 消</el-button>
          <el-button type="primary" @click="submitForm4()">确 定</el-button>
        </span>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	export default {
		name: "department",
		data() {
			return {
				currentRowIndex: 0,
				transferTitles: ['待关联', '已关联'],
				transferList: [],
				OperatorList2: [],
				OperatorList3: [],
				guanLian: {
					adminSnos: [],
					deptid: '',
					type: '',
				},
				deptTree: [], //部门树
				defaultCheckedKeys: [],
				defaultProps: {
					children: 'children',
					label: 'text'
				},
				dialogVisible: false, //添加
				dialogVisible1: false, //修改
				dialogVisible2: false, //关联
				dialogVisible3: false, //关联
				dialogVisible4: false, //关联
				tableData: [],
				administrator: {
					dept: '',
					limit: '', //管理员等级 1：超级管理员 2：院系管理员
					username: '',
					userId: '', //管理员id
				},
				total: 0,
				addData: {
					name: '',
				},
				editData: {
					id: '',
					name: '',
				},
				rules: {
					name: [{
						required: true,
						message: '请输入院系名称',
						trigger: 'blur'
					}],
				},
				query: { //搜索
					name: '',
					page: 1,
					size: 10,
				},
				filterMethod(query, item) {
					return item.label.indexOf(query) > -1;
				},
				filterMethod2(query, item) {
					return item.label.indexOf(query) > -1;
				}
			};
		},

		created() {
			let that = this;
			that.GetTaleList();
			that.fetchDeptTree();
		},
		methods: {
			changeTransferHandle(cVal, direction, dataArr) {
				let that = this;
				let apiUrl;
				let paramData = null;
				switch(direction) {
					case 'right':
						apiUrl = '/Organization/AddCorsOrAdmins';
						that.guanLian.adminSnos = dataArr;
						paramData = that.guanLian;
						break;
					case 'left':
						apiUrl = '/Organization/DelOrgCorsOrAdmins';
						let pArr = [];
						let admins = that.tableData[that.currentRowIndex].admins;
						for(let i = 0; i < dataArr.length; i++) {
							for(let j = 0; j < admins.length; j++) {
								if(dataArr[i] == admins[j].sno) {
									pArr.push(admins[j].id);
								}
							}
						}
						paramData = pArr;
						break;
					default:
						break;
				}

				that.postAxios(apiUrl, paramData).then((res) => {
					if(res.code == 0) {
						that.$notify({
							title: '成功',
							message: '操作成功',
							type: 'success'
						});
						that.GetTaleList();
					} else {
						that.$notify.error({
							title: '错误',
							message: '操作失败'
						});
					}
				})
			},
			//获取所有操作员
			GetOperatorList() {
				let that = this;
				that.postAxios("/Operator/Page", {
					"PageInfo": {
						"pageIndex": 1,
						"pageSize": 2000
					},
					"Conditions": {
						"name": "",
						"sno": "",
					}
				}).then((res) => {
					if(res.code == 0) {
						let arr = res.page.data;
						let nArr2 = [];
						let nArr3 = [];
						for(let i = 0; i < arr.length; i++) {
							//roleid 2:辅导员 3：院系管理员
							if(arr[i].roleid == 2) {
								nArr2.push({
									key: arr[i].sno,
									label: arr[i].name + '(' + arr[i].sno + ')',
									disabled: false
								});
							} else if(arr[i].roleid == 3) {
								nArr3.push({
									key: arr[i].sno,
									label: arr[i].name + '(' + arr[i].sno + ')',
									disabled: false
								});
							}
						}
						that.OperatorList2 = nArr2;
						that.OperatorList3 = nArr3;
					}
				})
			},
			//获取所有部门树形结构
			fetchDeptTree() {
				let that = this;
				that.postAxios("/Organization/GetDetpTree?root=%", null).then((res) => {
					if(res.code == 0) {
						that.deptTree = res.data;
						console.log(that.deptTree, 'that.deptTree')
					}
				})
			},
			//获取部门树形结构 院系已关联的
			fetchDeptTreeGuanLian(deptid) {
				let that = this;
				that.postAxios("/Organization/GetOrgSynDept?deptid=" + deptid, null).then((res) => {
					if(res.code == 0) {
						let arr = res.data;
						let idArr = [];
						for(let i = 0; i < arr.length; i++) {
							idArr.push(arr[i].primary);
						}
						//						//清空默认勾选的项
						that.$refs.tree.setCheckedKeys([]);
						that.defaultCheckedKeys = idArr
						console.log('that.defaultCheckedKeys', that.defaultCheckedKeys)
					}
				})
			},
			//搜索
			searchHandle() {
				this.query.page = 1;
				this.query.size = 10;
				this.GetTaleList();
			},
			//获取表格数据
			GetTaleList() {
				let that = this;
				that.postAxios("/Organization/Page", {
					"PageInfo": {
						"pagendex": that.query.page,
						"pageSize": that.query.size
					},
					"Conditions": {
						"name": that.query.name,
					}
				}).then((res) => {
					if(res.code == 0) {
						that.tableData = res.page.data;
						that.total = res.page.count;
					}
				})
			},
			//分页
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.query.size = val;
				this.GetTaleList();
			},
			//分页
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.query.page = val;
				this.GetTaleList();
			},
			//添加按钮
			addHandle() {
				this.dialogVisible = true;
			},
			//编辑
			editHandle(row) {
				this.dialogVisible1 = true;
				this.editData.id = row.id;
				this.editData.name = row.name;
			},
			//删除
			deleteHandle(row) {
				let that = this;
				this.$confirm('此操作将永久删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.postAxios("/Organization/DeleteOrg?deptid=" + row.id, null)
						.then((res) => {
							if(res.code == 0) {
								that.$notify({
									title: '成功',
									message: '操作成功',
									type: 'success'
								});
								that.GetTaleList();
							} else {
								that.$notify.error({
									title: '错误',
									message: '操作失败'
								});
							}
						})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			//关联操作员 type：1 辅导员、2：院系管理员 index: 列表数据的序号
			guanLianHandle(row, index, type) {
				this.GetOperatorList();
				switch(type) {
					case 1:
						this.dialogVisible2 = true;
						break;
					case 2:
						this.dialogVisible3 = true;
						break;
					default:
						break;
				}
				this.guanLian.deptid = row.id;
				this.guanLian.type = type;
				let admins = row.admins;
				this.currentRowIndex = index;
				let arr = [];
				for(let i = 0; i < admins.length; i++) {
					arr.push(admins[i].sno);
				}
				this.transferList = arr;
			},
			//关联部门
			guanLianHandle4(row, index) {
				//清空默认勾选的项
				this.dialogVisible4 = true;
				this.currentRowIndex = index;
				this.fetchDeptTreeGuanLian(row.id);
			},
			//增加
			submitForm(formName) {
				let that = this;
				this.$refs[formName].validate((valid) => {
					if(valid) {
						that.postAxios("/Organization/AddOrg", that.addData).then((res) => {
							if(res.code == 0) {
								that.$notify({
									title: '成功',
									message: '操作成功',
									type: 'success'
								});
								that.GetTaleList();
							} else {
								that.$notify.error({
									title: '错误',
									message: '操作失败'
								});
							}
							that.dialogVisible = false;
						})
					} else {
						console.log('error submit!!');
					}
				});
			},
			//修改
			submitForm1(formName) {
				let that = this;
				this.$refs[formName].validate((valid) => {
					if(valid) {
						that.postAxios("/Organization/EditOrg", that.editData).then((res) => {
							if(res.code == 0) {
								that.$notify({
									title: '成功',
									message: '操作成功',
									type: 'success'
								});
								that.GetTaleList();
							} else {
								that.$notify.error({
									title: '错误',
									message: '操作失败'
								});
							}
							that.dialogVisible1 = false;
						})
					} else {
						console.log('error submit!!');
					}
				});
			},
			//关联部门
			submitForm4() {
				let that = this;
				let objArr = [];
				let nObjArr = [];
				//取最低层部门
				objArr = that.$refs.tree.getCheckedNodes();
				// nObjArr = objArr.filter(function(item) {
				// 	return item.isleaf;
				// })
				//取部门id
				let codeArr = [];
				codeArr = objArr.map(function(item) {
					return item.id;
				});
				let opt = {
					"deptid": that.tableData[that.currentRowIndex].id,
					"deptCodes": codeArr
				}
				that.postAxios("/Organization/AddDeptStusBySynDept", opt).then((res) => {
					if(res.code == 0) {
						that.$notify({
							title: '成功',
							message: '操作成功',
							type: 'success'
						});
					} else {
						that.$notify.error({
							title: '错误',
							message: '操作失败'
						});
					}
					that.dialogVisible4 = false;
				})
			}

		}
	};
</script>

<style scoped lang="scss">
	.w400 {
		width: 400px;
	}
	
	.manage {
		height: 100%;
		width: 100%;
	}
	
	.mar_rig10 {
		margin-right: 10px;
	}
	
	.manage_content {
		.search_wrap {
			padding: 10px 0px;
			display: flex;
			align-items: center;
			flex-wrap: wrap;
		}
		.search_wrap .el-input,
		.search_wrap .el-select {
			width: 200px;
			margin: 5px 10px 5px 0;
		}
		.search_wrap .el-button {
			/*margin: 0 10px 10px 0;*/
		}
		.pagination_wrap {
			background: #fff;
			padding: 30px 0;
			display: flex;
			justify-content: space-around;
			align-items: center;
		}
	}
</style>
<style>
	.my_transfer {
		display: flex;
		justify-content: center;
	}
	
	.my_transfer .el-transfer__button:first-child {
		margin-bottom: 0px;
	}
	
	.my_transfer .el-transfer-panel {
		width: 240px;
	}
	.el-tree {
		height: 400px;
		overflow-y: scroll;
	}
</style>